package com.example.sunmiv1.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.WarehousingAdapter;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import com.example.sunmiv1.entity.WarehousingDetailInfo;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


// 入庫單  入庫
public class WarehousingActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.warehousing_edit)
    EditText warehousingEdit;
    @BindView(R.id.warehousing_code)
    ImageView warehousingCode;
    @BindView(R.id.warehousing_search)
    ImageView warehousingSearch;
    @BindView(R.id.warehousing_listView)
    ListView warehousingListView;
    @BindView(R.id.warehousing_checkAll)
    TextView warehousingCheckAll;
    @BindView(R.id.warehousing_submit)
    TextView warehousingSubmit;
    @BindView(R.id.warehousing_complete)
    TextView warehousingComplete;
    @BindView(R.id.warehousing_delete)
    TextView warehousingDelete;
    @BindView(R.id.warehousing_operation)
    LinearLayout warehousingOperation;
    @BindView(R.id.remark)
    EditText remark;
    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;

    private WarehousingDetailInfo warehousingDetailInfo;
    private List<WarehousingDetailInfo.DataBean> list = new ArrayList<>();
    private List<WarehousingDetailInfo.DataBean> refuseList = new ArrayList<>();
    private WarehousingAdapter warehousingAdapter;
    public static boolean opera = false;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    for (WarehousingDetailInfo.DataBean dataBean : warehousingDetailInfo.getData()) {
                        dataBean.setSerialList(dataBean.getSerial_list());
                        list.add(dataBean);
                    }
                    setWarehousingAdapter();
                    break;
                case 2:
                    setWarehousingAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_warehousing);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.warehousingTitle1);
        context = this;
        aCache = ACache.get(context);
        Intent intent = new Intent();

        // 設置返回碼和返回攜帶的數據
        setResult(1, intent);
        loadingDialog = new LoadingDialog(context);
        getInfo();
    }

    @OnClick({R.id.title_back, R.id.warehousing_code, R.id.warehousing_search, R.id.warehousing_checkAll,
            R.id.warehousing_submit, R.id.warehousing_complete, R.id.warehousing_delete, R.id.warehousing_operation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.warehousing_code://掃碼
                startQrCode();
                break;
            case R.id.warehousing_search://搜索商品
                if (TextUtils.isEmpty(warehousingEdit.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入貨號/條碼/名稱", Toast.LENGTH_SHORT).show();
                    return;
                }
                String info = warehousingEdit.getText().toString().trim();
                for (int i = 0; i < list.size(); i++) {
                    if (info.equals(list.get(i).getGoods_code())) {
                        warehousingListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        warehousingListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                warehousingListView.setSelection(finalI);
                            }
                        }, 800);
                        warehousingAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getSku_code())) {
                        warehousingListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        warehousingListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                warehousingListView.setSelection(finalI);
                            }
                        }, 800);
                        warehousingAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getGoods_number())) {
                        warehousingListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        warehousingListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                warehousingListView.setSelection(finalI);
                            }
                        }, 800);
                        warehousingAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getSku_goods_number())) {
                        warehousingListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        warehousingListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                warehousingListView.setSelection(finalI);
                            }
                        }, 800);
                        warehousingAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getGoods_name())) {
                        warehousingListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        warehousingListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                warehousingListView.setSelection(finalI);
                            }
                        }, 800);
                        warehousingAdapter.setSelect(i);
                        break;
                    }
                }
                break;
            case R.id.warehousing_checkAll:
                opera = true;
                if (warehousingSubmit.getVisibility() == View.GONE) {
                    if ("全選".equals(warehousingCheckAll.getText().toString().trim())) {
                        for (WarehousingDetailInfo.DataBean dataBean : list) {
                            dataBean.setChecked(true);
                        }
                        warehousingCheckAll.setText(R.string.purRefundAdding_Choose_Item_Check_None);
                    } else {
                        for (WarehousingDetailInfo.DataBean dataBean : list) {
                            dataBean.setChecked(false);
                        }
                        warehousingCheckAll.setText(R.string.purRefundAdding_check_all);
                    }
                } else {
                    warehousingSubmit.setVisibility(View.GONE);
                    warehousingOperation.setVisibility(View.VISIBLE);
                    warehousingCheckAll.setText(R.string.purRefundAdding_check_all);
                }
                setWarehousingAdapter();
                break;
            case R.id.warehousing_submit:
                if (list.size() == 0) {
                    Toast.makeText(context, "請先選擇商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getWarehouse_num() <= 0) {
                        Toast.makeText(context, "請先修改" + list.get(i).getGoods_name() + "的入庫數量", Toast.LENGTH_SHORT).show();
                        warehousingListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        warehousingListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                warehousingListView.setSelection(finalI);
                            }
                        }, 800);
                        warehousingAdapter.setSelect(i);
                        return;
                    }
                    if (list.get(i).getWarehouse_price() <= 0) {
                        Toast.makeText(context, "請先修改" + list.get(i).getGoods_name() + "的參考調撥價", Toast.LENGTH_SHORT).show();
                        warehousingListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        warehousingListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                warehousingListView.setSelection(finalI);
                            }
                        }, 800);
                        warehousingAdapter.setSelect(i);
                        return;
                    }
                    if (list.get(i).getWarehouse_num() < list.get(i).getStock_num()) {
                        WarehousingDetailInfo.DataBean dataBean = new WarehousingDetailInfo.DataBean(list.get(i));
                        dataBean.setWarehouse_num(list.get(i).getStock_num() - list.get(i).getWarehouse_num());
                        List<WarehousingDetailInfo.DataBean.SerialListBean> a = new ArrayList<>();//入庫的串號
                        List<WarehousingDetailInfo.DataBean.SerialListBean> b = new ArrayList<>();//拒收的串號
                        for (WarehousingDetailInfo.DataBean.SerialListBean bean : list.get(i).getSerialList()) {
                            if (bean.isCheck()) {
                                b.add(bean);
                            } else {
                                a.add(bean);
                            }
                        }
                        list.get(i).setSerial_list(a);
                        dataBean.setSerial_list(b);
                        refuseList.add(dataBean);
                    }
                }
                goodsVerification();
                break;
            case R.id.warehousing_complete:
                opera = false;
                warehousingSubmit.setVisibility(View.VISIBLE);
                warehousingOperation.setVisibility(View.GONE);
                warehousingCheckAll.setText(R.string.operation);
                setWarehousingAdapter();
                break;
            case R.id.warehousing_delete:
                int size = list.size();
                for (int i = 0; i < size; i++) {
                    if (list.get(i).isChecked()) {
                        list.get(i).setWarehouse_num(0);
                        refuseList.add(list.remove(i));
                        i--;
                        size = list.size();
                    }
                }
                setWarehousingAdapter();
                break;
            case R.id.warehousing_operation:
                break;
        }
    }

    private void setWarehousingAdapter() {
        if (warehousingAdapter == null) {
            warehousingAdapter = new WarehousingAdapter(context, list);
            warehousingListView.setAdapter(warehousingAdapter);
        } else {
            warehousingAdapter.notifyDataSetChanged();
        }
        warehousingAdapter.setChoose(index -> {
            Intent intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 16);
            intent.putExtra("good", list.get(index));
            startActivityForResult(intent, 200);
        });
    }

    /*獲取入庫詳情*/
    private void getInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("id", getIntent().getStringExtra("id"));
            jsonObject.put("type", getIntent().getStringExtra("type"));
            HttpUtils.post(context, Common.GET_ENTER_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    warehousingDetailInfo = GsonUtils.JsonToBean(text, WarehousingDetailInfo.class);
                    Message msg = new Message();
                    if (warehousingDetailInfo.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*判斷商品*/
    private void goodsVerification() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("id", getIntent().getStringExtra("id"));
            jsonObject.put("type", getIntent().getStringExtra("type"));
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("goodsList", new Gson().toJson(list));
            jsonObject.put("refuseList", new Gson().toJson(refuseList));
            HttpUtils.post(context, Common.GOODS_VERIFICATION, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {//可以入庫
                            operation();
                        } else if (json.getInt("status") == 3) {//
                            int idLength = json.getJSONArray("goodsIds").length();
                            JSONArray goods = json.getJSONArray("goodsIds");
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setTitle("入庫");
                            builder.setMessage(json.getString("msg"));
                            builder.setPositiveButton("確定", (dialog, which) -> {
                                String goodsId = "";
                                for (int i = 0; i < idLength; i++) {
                                    try {
                                        goodsId = goodsId + "," + goods.getString(i);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                goodsId = goodsId.substring(1);
                                batchSync(goodsId);
                            });
                            builder.setNegativeButton("取消", (dialog, which) -> {

                            });
                            //一樣要show
                            builder.show();
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*同步商品*/
    private void batchSync(String goodsId) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("goodsIds", goodsId);
            jsonObject.put("type", getIntent().getStringExtra("type"));
            HttpUtils.post(context, Common.BATCH_SYNC, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            operation();
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*入庫*/
    private void operation() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("id", getIntent().getStringExtra("id"));
            jsonObject.put("type", getIntent().getStringExtra("type"));
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("order_number", getIntent().getStringExtra("orderNo"));
            jsonObject.put("remarks", remark.getText().toString().trim());
            jsonObject.put("goodsList", new Gson().toJson(list));
            jsonObject.put("refuseList", new Gson().toJson(refuseList));
            HttpUtils.post(context, Common.ENTER_OPERATION, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        //Log.e(TAG, "onActivityResult: " + data);
        if (data != null) {
            switch (requestCode) {
                case Constant.REQ_QR_CODE:
                    Bundle bundle = data.getExtras();
                    warehousingEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    String info = warehousingEdit.getText().toString().trim();
                    for (int i = 0; i < list.size(); i++) {
                        if (info.equals(list.get(i).getGoods_code())) {
                            warehousingListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            warehousingListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    warehousingListView.setSelection(finalI);
                                }
                            }, 800);
                            warehousingAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(list.get(i).getSku_code())) {
                            warehousingListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            warehousingListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    warehousingListView.setSelection(finalI);
                                }
                            }, 800);
                            warehousingAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(list.get(i).getGoods_number())) {
                            warehousingListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            warehousingListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    warehousingListView.setSelection(finalI);
                                }
                            }, 800);
                            warehousingAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(list.get(i).getSku_goods_number())) {
                            warehousingListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            warehousingListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    warehousingListView.setSelection(finalI);
                                }
                            }, 800);
                            warehousingAdapter.setSelect(i);
                            break;
                        }
                    }
                    break;
                case 200:
                    WarehousingDetailInfo.DataBean bean = (WarehousingDetailInfo.DataBean) data.getSerializableExtra("bean");
                    int index = 0;
                    for (int t = 0; t < list.size(); t++) {
                        if (bean.getGoods_id().equals(list.get(t).getGoods_id())) {
                            if ("2".equals(bean.getAttribute_state())) {
                                if (bean.getSku_id().equals(list.get(t).getSku_id())) {
                                    index = t;
                                    break;
                                }
                            } else {
                                index = t;
                                break;
                            }
                        }
                    }
                    list.set(index, bean);
                    setWarehousingAdapter();
                    break;
            }
        }

    }

}
